<?php defined('SYSPATH') or die('No direct script access.');
include BASEPATH . "/plugins/alipay/vendor/Alipay/AopClient.php";
/**
 *Copyright www.stourweb.com
 *Author: GJX
 *QQ: 727612896
 *Time: 2021/5/11 10:37
 *Desc: 支付宝小程序支付
 */
class Controller_Pc_Alipayxcx extends Stourweb_Controller
{

    /**
     * @function 服务器异步通知页面路径
     * @return string
     */
    public function action_notify_url()
    {
        self::_write_log($this->request->action());

        $data = $_POST;
        $config = Model_Sysconfig::get_configs(0,array('cfg_zhifubao_alipay_public_key'),0);
        $aop = new AopClient;
        $aop->alipayrsaPublicKey = $config['alipay_public_key'];
        $flag = $aop->rsaCheckV1($data, NULL, "RSA2");

        if($flag){
            self::order_status_chang($data);
        }

        echo 'success';
    }

    public function order_status_chang($data)
    {
        $order_arr = explode('_',$data['out_trade_no']);
        $online_transaction_no = array('source'=>'alipay','trade_no'=>$data['trade_no']);
        if (St_Payment::total_fee_confirm($order_arr[0], $data['buyer_pay_amount']))
        {
            $payset = Model_Payset::get_payset_info_by_id(1);
            St_Payment::pay_success($order_arr[0], $payset['name'] . '(zfb小程序)');
            //写入微信订单号
            DB::update('member_order')->set(array('online_transaction_no'=>json_encode($online_transaction_no)))->where('ordersn','=',$order_arr[0])->execute();
        }
    }

    /**
     * @function 将回调参数写入日志文件
     * @param $method
     */
    private static function _write_log($method)
    {
        $pay_class = __CLASS__;
        $pay_log_dir = BASEPATH . 'plugins/alipay/logs/pay/';
        if (! file_exists($pay_log_dir))
        {
            mkdir($pay_log_dir, 0777, true);
        }
        //日志文件
        $file = $pay_log_dir . str_replace('pay_', '', strtolower($pay_class)) . '_' . date('ymd') . '.txt';
        $data = "\r\n[{$method}:" . date('YmdHis');
        foreach ($_REQUEST as $k => $v)
        {
            $data .= " {$k}={$v}";
        }
        $data .= ']';
        file_put_contents($file, $data, FILE_APPEND);
    }


    /**
     * @function 获取远程数据
     * @param $url
     * @return mixed
     */
    public function file_get_content($url) {
        $ch=  curl_init($url);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $content = curl_exec($ch);
        curl_close($ch);
        return $content;
    }
}